package com.service.impl;

import com.dto.NoteCreateDTO;
import com.dto.NoteWithUserDTO;
import com.mapper.NoteTagsMapper;
import com.mapper.NotesMapper;
import com.mapper.TagsMapper;
import com.pojo.NoteTags;
import com.pojo.Notes;
import com.pojo.Result;
import com.service.NotesService;
import com.utils.ThreadLocalUtil;
import com.vo.NoteWithStatsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class NotesServiceImpl implements NotesService {

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private NoteTagsMapper  noteTagsMapper;

    @Transactional
    public Result<Void> createNoteWithTags(NoteCreateDTO dto) {
        try {
            Notes note = new Notes();
            note.setUserId(dto.getUserId());
            note.setTitle(dto.getTitle());
            note.setContent(dto.getContent());
            note.setIsPrivate(dto.getIsPrivate());
            note.setCoverImageUrl(dto.getCoverImageUrl());
            note.setCreatedAt(LocalDateTime.now());
            note.setUpdatedAt(LocalDateTime.now());

            notesMapper.insert(note);
            Integer noteId = note.getId();

            if (dto.getTagIds() != null && !dto.getTagIds().isEmpty()) {
                for (Integer tagId : dto.getTagIds()) {
                    noteTagsMapper.insert(new NoteTags(noteId, tagId, LocalDateTime.now()));
                }
            }
            return Result.success();
        } catch (Exception e) {

            return Result.error("创建失败");
        }
    }


    @Override
    public Integer getAuthorIdByNoteId(Integer noteId) {
        return notesMapper.selectAuthorIdByNoteId(noteId);
    }

    @Override
    public Result<Void> updateNote(Notes note) {
        try {
            // 设置更新时间
            note.setUpdatedAt(LocalDateTime.now());

            int result = notesMapper.update(note);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("更新笔记失败，可能ID不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> deleteNote(Integer id) {
        try {
            int result = notesMapper.delete(id);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("删除笔记失败，可能ID不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<NoteWithUserDTO> getNoteById(Integer id) {

        try {
            NoteWithUserDTO note = notesMapper.selectById(id);
            if (note != null) {
                return Result.success(note);
            } else {
                return Result.error("笔记不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }

    }



    @Override
    public List<NoteWithStatsVO> getLikedNotesWithStats(Integer userId) {
        return notesMapper.selectLikedNotesWithStats(userId);
    }

    @Override
    public List<NoteWithStatsVO> getCollectedNotesWithStats(Integer userId) {
        return notesMapper.selectCollectedNotesWithStats(userId);
    }
    

    @Override
    public Result<Void> updateNotePrivacy(Integer id, Boolean isPrivate) {
        try {
            int result = notesMapper.updatePrivacy(id, isPrivate);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("更新笔记隐私状态失败，可能ID不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }





    @Override
    public Result<List<NoteWithStatsVO>> getRecentPublicNotesWithStats(Integer userId, int limit) {
        return Result.success(notesMapper.selectNotesWithStats(userId, limit));
    }

    @Override
    public List<NoteWithStatsVO> getUserNotesWithStats(Integer userId, Integer currentUserId) {
        return notesMapper.selectUserNotesWithStats(userId, currentUserId);
    }


    @Override
    public List<NoteWithStatsVO> getPublicNotesByTagWithStats(Integer tagId, int limit, Integer currentUserId) {
        return notesMapper.selectPublicNotesByTagWithStats(tagId, limit, currentUserId);
    }

}